<!DOCTYPE html><html lang="zh"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no,minimal-ui"><meta name="renderer" content="webkit"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><meta name="format-detection" content="telephone=no,email=no,adress=no"><meta name="theme-color" content="#000000"><meta http-equiv="window-target" content="_top"><title>FastAPI | 教程 | 查询参数和字符串校验 | 你过来啊！</title><meta name="description" content="https:&#x2F;&#x2F;fastapi.tiangolo.com&#x2F;zh&#x2F;tutorial&#x2F;query-params-str-validations&#x2F;  查询参数和字符串校验FastAPI 允许你为参数声明额外的信息和校验。 让我们以下面的应用程序为例： 12345678910111213from typing import Optionalfrom fastapi import FastAPIapp &#x3D;"><meta property="og:type" content="article"><meta property="og:title" content="FastAPI | 教程 | 查询参数和字符串校验"><meta property="og:url" content="https://xuqinmin.gitee.io/posts/732748453.html"><meta property="og:site_name" content="你过来啊！"><meta property="og:description" content="https:&#x2F;&#x2F;fastapi.tiangolo.com&#x2F;zh&#x2F;tutorial&#x2F;query-params-str-validations&#x2F;  查询参数和字符串校验FastAPI 允许你为参数声明额外的信息和校验。 让我们以下面的应用程序为例： 12345678910111213from typing import Optionalfrom fastapi import FastAPIapp &#x3D;"><meta property="og:locale" content="zh_CN"><meta property="og:image" content="https://xuqinmin.com/images/fastapi/08/image02_2.png"><meta property="og:image" content="https://xuqinmin.com/images/fastapi/08/image01_2.png"><meta property="article:published_time" content="2020-09-24T08:26:08.000Z"><meta property="article:modified_time" content="2020-09-24T09:17:15.567Z"><meta property="article:author" content="Xuqm"><meta property="article:tag" content="fastapi"><meta property="article:tag" content="后端"><meta name="twitter:card" content="summary"><meta name="twitter:image" content="https://xuqinmin.com/images/fastapi/08/image02_2.png"><link rel="canonical" href="https://xuqinmin.gitee.io/posts/732748453.html"><link rel="alternate" href="/atom.xml" title="你过来啊！" type="application/atom+xml"><link rel="icon" href="/images/favicon.png" type="image/x-icon"><link rel="stylesheet" href="/css/style.css"><link href="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.3.5/dist/jquery.fancybox.min.css" rel="stylesheet"><meta name="generator" content="Hexo 5.4.2"></head><body class="main-center" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="slimContent"><div class="navbar-header"><div class="profile-block text-center"><a id="avatar" href="https://xuqinmin.com/xuqinmin12" target="_blank"><img class="img-circle img-rotate" src="/images/avatar.jpg" width="200" height="200"></a><h2 id="name" class="hidden-xs hidden-sm">XUQM</h2><h3 id="title" class="hidden-xs hidden-sm hidden-md">Android开发</h3><small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> Beijing, China</small></div><div class="search" id="search-form-wrap"><form class="search-form sidebar-form"><div class="input-group"><input type="text" class="search-form-input form-control" placeholder="搜索"> <span class="input-group-btn"><button type="submit" class="search-form-submit btn btn-flat" onclick="return!1"><i class="icon icon-search"></i></button></span></div></form><div class="ins-search"><div class="ins-search-mask"></div><div class="ins-search-container"><div class="ins-input-wrapper"><input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech> <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button></div><div class="ins-section-wrapper"><div class="ins-section-container"></div></div></div></div></div><button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false"><span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span></button></div><nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation"><ul class="nav navbar-nav main-nav menu-highlight"><li class="menu-item menu-item-home"><a href="/"><i class="icon icon-home-fill"></i> <span class="menu-title">首页</span></a></li><li class="menu-item menu-item-archives"><a href="/archives"><i class="icon icon-archives-fill"></i> <span class="menu-title">归档</span></a></li><li class="menu-item menu-item-categories"><a href="/categories"><i class="icon icon-folder"></i> <span class="menu-title">分类</span></a></li><li class="menu-item menu-item-tags"><a href="/tags"><i class="icon icon-tags"></i> <span class="menu-title">标签</span></a></li><li class="menu-item menu-item-repository"><a href="/repository"><i class="icon icon-project"></i> <span class="menu-title">项目</span></a></li><li class="menu-item menu-item-about"><a href="/about"><i class="icon icon-cup-fill"></i> <span class="menu-title">关于</span></a></li></ul><ul class="social-links"><li><a href="https://github.com/xuqm" target="_blank" title="Github" data-toggle="tooltip" data-placement="top"><i class="icon icon-github"></i></a></li><li><a href="https://gitee.com/xuqinmin" target="_blank" title="Gitee" data-toggle="tooltip" data-placement="top"><i class="icon icon-gitee"></i></a></li><li><a href="/atom.xml" target="_blank" title="Rss" data-toggle="tooltip" data-placement="top"><i class="icon icon-rss"></i></a></li></ul></nav></div></header><aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar"><div class="slimContent"><div class="widget"><h3 class="widget-title">公告</h3><div class="widget-body"><div id="board"><div class="content"><p>欢迎交流与分享经验!</p></div></div></div></div><div class="widget"><h3 class="widget-title">分类</h3><div class="widget-body"><ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Android/">Android</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Flutter/">Flutter</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/python/">python</a><span class="category-list-count">19</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/python/django/">django</a><span class="category-list-count">6</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/%E5%89%8D%E7%AB%AF/">前端</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a><span class="category-list-count">10</span></li></ul></div></div><div class="widget"><h3 class="widget-title">标签</h3><div class="widget-body"><ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/Android/" rel="tag">Android</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Flutter/" rel="tag">Flutter</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/React-Native/" rel="tag">React Native</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/android/" rel="tag">android</a><span class="tag-list-count">13</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/css/" rel="tag">css</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/django/" rel="tag">django</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/fastapi/" rel="tag">fastapi</a><span class="tag-list-count">13</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/ios/" rel="tag">ios</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/java/" rel="tag">java</a><span class="tag-list-count">10</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/kotlin/" rel="tag">kotlin</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/python/" rel="tag">python</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/restframework/" rel="tag">restframework</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E5%90%8E%E7%AB%AF/" rel="tag">后端</a><span class="tag-list-count">13</span></li></ul></div></div><div class="widget"><h3 class="widget-title">标签云</h3><div class="widget-body tagcloud"><a href="/tags/Android/" style="font-size:13.25px">Android</a> <a href="/tags/Flutter/" style="font-size:13.25px">Flutter</a> <a href="/tags/React-Native/" style="font-size:13px">React Native</a> <a href="/tags/android/" style="font-size:14px">android</a> <a href="/tags/css/" style="font-size:13.5px">css</a> <a href="/tags/django/" style="font-size:13.5px">django</a> <a href="/tags/fastapi/" style="font-size:14px">fastapi</a> <a href="/tags/ios/" style="font-size:13.25px">ios</a> <a href="/tags/java/" style="font-size:13.75px">java</a> <a href="/tags/kotlin/" style="font-size:13.25px">kotlin</a> <a href="/tags/python/" style="font-size:13.5px">python</a> <a href="/tags/restframework/" style="font-size:13.5px">restframework</a> <a href="/tags/%E5%90%8E%E7%AB%AF/" style="font-size:14px">后端</a></div></div><div class="widget"><h3 class="widget-title">归档</h3><div class="widget-body"><ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2023/05/">五月 2023</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/10/">十月 2020</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/09/">九月 2020</a><span class="archive-list-count">13</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/05/">五月 2020</a><span class="archive-list-count">12</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/04/">四月 2020</a><span class="archive-list-count">12</span></li></ul></div></div><div class="widget"><h3 class="widget-title">最新文章</h3><div class="widget-body"><ul class="recent-post-list list-unstyled no-thumbnail"><li><div class="item-inner"><p class="item-category"><a class="category-link" href="/categories/Android/">Android</a></p><p class="item-title"><a href="/posts/217975334.html" class="title">Android日常错误记录</a></p><p class="item-date"><time datetime="2023-05-29T05:54:35.000Z" itemprop="datePublished">2023-05-29</time></p></div></li><li><div class="item-inner"><p class="item-category"><a class="category-link" href="/categories/Flutter/">Flutter</a></p><p class="item-title"><a href="/posts/899076041.html" class="title">跨平台方案 |Flutter |Flutter浅尝</a></p><p class="item-date"><time datetime="2020-10-30T08:47:15.000Z" itemprop="datePublished">2020-10-30</time></p></div></li><li><div class="item-inner"><p class="item-category"><a class="category-link" href="/categories/Flutter/">Flutter</a></p><p class="item-title"><a href="/posts/3421344940.html" class="title">跨平台方案 |Flutter |Flutter与RN简单对比</a></p><p class="item-date"><time datetime="2020-10-23T08:57:35.000Z" itemprop="datePublished">2020-10-23</time></p></div></li><li><div class="item-inner"><p class="item-category"><a class="category-link" href="/categories/python/">python</a></p><p class="item-title"><a href="/posts/3925265046.html" class="title">FastAPI | 教程 | 额外的模式</a></p><p class="item-date"><time datetime="2020-09-25T03:15:34.000Z" itemprop="datePublished">2020-09-25</time></p></div></li><li><div class="item-inner"><p class="item-category"><a class="category-link" href="/categories/python/">python</a></p><p class="item-title"><a href="/posts/3208273745.html" class="title">FastAPI | 教程 | 请求体-嵌套模型</a></p><p class="item-date"><time datetime="2020-09-24T09:51:35.000Z" itemprop="datePublished">2020-09-24</time></p></div></li></ul></div></div></div></aside><aside class="sidebar sidebar-toc collapse in" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar"><div class="slimContent"><nav id="toc" class="article-toc"><h3 class="toc-title">文章目录</h3><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%9F%A5%E8%AF%A2%E5%8F%82%E6%95%B0%E5%92%8C%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%A0%A1%E9%AA%8C"><span class="toc-number">1.</span> <span class="toc-text">查询参数和字符串校验</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A2%9D%E5%A4%96%E7%9A%84%E6%A0%A1%E9%AA%8C"><span class="toc-number">1.1.</span> <span class="toc-text">额外的校验</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%BC%E5%85%A5-Query"><span class="toc-number">1.1.1.</span> <span class="toc-text">导入 Query</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-Query-%E4%BD%9C%E4%B8%BA%E9%BB%98%E8%AE%A4%E5%80%BC"><span class="toc-number">1.2.</span> <span class="toc-text">使用 Query 作为默认值</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0%E6%9B%B4%E5%A4%9A%E6%A0%A1%E9%AA%8C"><span class="toc-number">1.3.</span> <span class="toc-text">添加更多校验</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-number">1.4.</span> <span class="toc-text">添加正则表达式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%BB%98%E8%AE%A4%E5%80%BC"><span class="toc-number">1.5.</span> <span class="toc-text">默认值</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A3%B0%E6%98%8E%E4%B8%BA%E5%BF%85%E9%9C%80%E5%8F%82%E6%95%B0"><span class="toc-number">1.6.</span> <span class="toc-text">声明为必需参数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%9F%A5%E8%AF%A2%E5%8F%82%E6%95%B0%E5%88%97%E8%A1%A8-%E5%A4%9A%E4%B8%AA%E5%80%BC"><span class="toc-number">1.7.</span> <span class="toc-text">查询参数列表 &#x2F; 多个值</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%B7%E6%9C%89%E9%BB%98%E8%AE%A4%E5%80%BC%E7%9A%84%E6%9F%A5%E8%AF%A2%E5%8F%82%E6%95%B0%E5%88%97%E8%A1%A8-%E5%A4%9A%E4%B8%AA%E5%80%BC"><span class="toc-number">1.7.1.</span> <span class="toc-text">具有默认值的查询参数列表 &#x2F; 多个值</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-list"><span class="toc-number">1.7.1.1.</span> <span class="toc-text">使用 list</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A3%B0%E6%98%8E%E6%9B%B4%E5%A4%9A%E5%85%83%E6%95%B0%E6%8D%AE"><span class="toc-number">1.8.</span> <span class="toc-text">声明更多元数据</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%AB%E5%90%8D%E5%8F%82%E6%95%B0"><span class="toc-number">1.9.</span> <span class="toc-text">别名参数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BC%83%E7%94%A8%E5%8F%82%E6%95%B0"><span class="toc-number">1.10.</span> <span class="toc-text">弃用参数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">1.11.</span> <span class="toc-text">总结</span></a></li></ol></li></ol></nav></div></aside><main class="main" role="main"><div class="content"><article id="post-FastApi---08教程-查询参数和字符串校验" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting"><div class="article-header"><h1 class="article-title" itemprop="name">FastAPI | 教程 | 查询参数和字符串校验</h1><div class="article-meta"><span class="article-date"><i class="icon icon-calendar-check"></i> <a href="/posts/732748453.html" class="article-date"><time datetime="2020-09-24T08:26:08.000Z" itemprop="datePublished">2020-09-24</time> </a></span><span class="article-category"><i class="icon icon-folder"></i> <a class="article-category-link" href="/categories/python/">python</a> </span><span class="article-tag"><i class="icon icon-tags"></i> <a class="article-tag-link-link" href="/tags/fastapi/" rel="tag">fastapi</a>, <a class="article-tag-link-link" href="/tags/%E5%90%8E%E7%AB%AF/" rel="tag">后端</a> </span><span class="article-read hidden-xs"><i class="icon icon-eye-fill" aria-hidden="true"></i> <span id="busuanzi_container_page_pv"><span id="busuanzi_value_page_pv">0</span> </span></span><span class="post-comment"><i class="icon icon-comment"></i> <a href="/posts/732748453.html#comments" class="article-comment-link">评论</a></span> <span class="post-wordcount hidden-xs" itemprop="wordCount">字数统计: 2.3k(字)</span> <span class="post-readcount hidden-xs" itemprop="timeRequired">阅读时长: 10(分)</span></div></div><div class="article-entry marked-body" itemprop="articleBody"><blockquote><p><a target="_blank" rel="noopener" href="https://fastapi.tiangolo.com/zh/tutorial/query-params-str-validations/">https://fastapi.tiangolo.com/zh/tutorial/query-params-str-validations/</a></p></blockquote><h1 id="查询参数和字符串校验"><a href="#查询参数和字符串校验" class="headerlink" title="查询参数和字符串校验"></a>查询参数和字符串校验</h1><p><strong>FastAPI</strong> 允许你为参数声明额外的信息和校验。</p><p>让我们以下面的应用程序为例：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">Optional</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.get(<span class="params"><span class="string">&quot;/items/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">read_items</span>(<span class="params">q: <span class="type">Optional</span>[<span class="built_in">str</span>] = <span class="literal">None</span></span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;items&quot;</span>: [&#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Foo&quot;</span>&#125;, &#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Bar&quot;</span>&#125;]&#125;</span><br><span class="line">    <span class="keyword">if</span> q:</span><br><span class="line">        results.update(&#123;<span class="string">&quot;q&quot;</span>: q&#125;)</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><p>查询参数 <code>q</code> 的类型为 <code>str</code>，默认值为 <code>None</code>，因此它是可选的。</p><h2 id="额外的校验"><a href="#额外的校验" class="headerlink" title="额外的校验"></a>额外的校验</h2><p>我们打算添加约束条件：即使 <code>q</code> 是可选的，但只要提供了该参数，则该参数值<strong>不能超过50个字符的长度</strong>。</p><h3 id="导入-Query"><a href="#导入-Query" class="headerlink" title="导入 Query"></a>导入 <code>Query</code></h3><p>为此，首先从 <code>fastapi</code> 导入 <code>Query</code>：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">Optional</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI, Query</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.get(<span class="params"><span class="string">&quot;/items/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">read_items</span>(<span class="params">q: <span class="type">Optional</span>[<span class="built_in">str</span>] = Query(<span class="params"><span class="literal">None</span>, max_length=<span class="number">50</span></span>)</span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;items&quot;</span>: [&#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Foo&quot;</span>&#125;, &#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Bar&quot;</span>&#125;]&#125;</span><br><span class="line">    <span class="keyword">if</span> q:</span><br><span class="line">        results.update(&#123;<span class="string">&quot;q&quot;</span>: q&#125;)</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><h2 id="使用-Query-作为默认值"><a href="#使用-Query-作为默认值" class="headerlink" title="使用 Query 作为默认值"></a>使用 <code>Query</code> 作为默认值</h2><p>现在，将 <code>Query</code> 用作查询参数的默认值，并将它的 <code>max_length</code> 参数设置为 50：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">Optional</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI, Query</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.get(<span class="params"><span class="string">&quot;/items/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">read_items</span>(<span class="params">q: <span class="type">Optional</span>[<span class="built_in">str</span>] = Query(<span class="params"><span class="literal">None</span>, max_length=<span class="number">50</span></span>)</span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;items&quot;</span>: [&#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Foo&quot;</span>&#125;, &#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Bar&quot;</span>&#125;]&#125;</span><br><span class="line">    <span class="keyword">if</span> q:</span><br><span class="line">        results.update(&#123;<span class="string">&quot;q&quot;</span>: q&#125;)</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><p>由于我们必须用 <code>Query(None)</code> 替换默认值 <code>None</code>，<code>Query</code> 的第一个参数同样也是用于定义默认值。</p><p>所以：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">q: <span class="built_in">str</span> = Query(<span class="literal">None</span>)</span><br></pre></td></tr></table></figure><p>…使得参数可选，等同于：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">q: <span class="built_in">str</span> = <span class="literal">None</span></span><br></pre></td></tr></table></figure><p>但是 <code>Query</code> 显式地将其声明为查询参数。</p><p>然后，我们可以将更多的参数传递给 <code>Query</code>。在本例中，适用于字符串的 <code>max_length</code> 参数：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">q: <span class="built_in">str</span> = Query(<span class="literal">None</span>, max_length=<span class="number">50</span>)</span><br></pre></td></tr></table></figure><p>将会校验数据，在数据无效时展示清晰的错误信息，并在 OpenAPI 模式的<em>路径操作</em>中记录该参数。</p><h2 id="添加更多校验"><a href="#添加更多校验" class="headerlink" title="添加更多校验"></a>添加更多校验</h2><p>你还可以添加 <code>min_length</code> 参数：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">Optional</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI, Query</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.get(<span class="params"><span class="string">&quot;/items/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">read_items</span>(<span class="params">q: <span class="type">Optional</span>[<span class="built_in">str</span>] = Query(<span class="params"><span class="literal">None</span>, min_length=<span class="number">3</span>, max_length=<span class="number">50</span></span>)</span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;items&quot;</span>: [&#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Foo&quot;</span>&#125;, &#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Bar&quot;</span>&#125;]&#125;</span><br><span class="line">    <span class="keyword">if</span> q:</span><br><span class="line">        results.update(&#123;<span class="string">&quot;q&quot;</span>: q&#125;)</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><h2 id="添加正则表达式"><a href="#添加正则表达式" class="headerlink" title="添加正则表达式"></a>添加正则表达式</h2><p>你可以定义一个参数值必须匹配的正则表达式：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">Optional</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI, Query</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.get(<span class="params"><span class="string">&quot;/items/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">read_items</span>(<span class="params"></span></span></span><br><span class="line"><span class="params"><span class="function">    q: <span class="type">Optional</span>[<span class="built_in">str</span>] = Query(<span class="params"><span class="literal">None</span>, min_length=<span class="number">3</span>, max_length=<span class="number">50</span>, regex=<span class="string">&quot;^fixedquery$&quot;</span></span>)</span></span></span><br><span class="line"><span class="params"><span class="function"></span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;items&quot;</span>: [&#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Foo&quot;</span>&#125;, &#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Bar&quot;</span>&#125;]&#125;</span><br><span class="line">    <span class="keyword">if</span> q:</span><br><span class="line">        results.update(&#123;<span class="string">&quot;q&quot;</span>: q&#125;)</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><p>这个指定的正则表达式通过以下规则检查接收到的参数值：</p><ul><li><code>^</code>：以该符号之后的字符开头，符号之前没有字符。</li><li><code>fixedquery</code>: 值精确地等于 <code>fixedquery</code>。</li><li><code>$</code>: 到此结束，在 <code>fixedquery</code> 之后没有更多字符。</li></ul><p>如果你对所有的这些<strong>「正则表达式」</strong>概念感到迷茫，请不要担心。对于许多人来说这都是一个困难的主题。你仍然可以在无需正则表达式的情况下做很多事情。</p><p>但是，一旦你需要用到并去学习它们时，请了解你已经可以在 <strong>FastAPI</strong> 中直接使用它们。</p><h2 id="默认值"><a href="#默认值" class="headerlink" title="默认值"></a>默认值</h2><p>你可以向 <code>Query</code> 的第一个参数传入 <code>None</code> 用作查询参数的默认值，以同样的方式你也可以传递其他默认值。</p><p>假设你想要声明查询参数 <code>q</code>，使其 <code>min_length</code> 为 <code>3</code>，并且默认值为 <code>fixedquery</code>：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI, Query</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.get(<span class="params"><span class="string">&quot;/items/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">read_items</span>(<span class="params">q: <span class="built_in">str</span> = Query(<span class="params"><span class="string">&quot;fixedquery&quot;</span>, min_length=<span class="number">3</span></span>)</span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;items&quot;</span>: [&#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Foo&quot;</span>&#125;, &#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Bar&quot;</span>&#125;]&#125;</span><br><span class="line">    <span class="keyword">if</span> q:</span><br><span class="line">        results.update(&#123;<span class="string">&quot;q&quot;</span>: q&#125;)</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><blockquote><p>具有默认值还会使该参数成为可选参数。</p></blockquote><h2 id="声明为必需参数"><a href="#声明为必需参数" class="headerlink" title="声明为必需参数"></a>声明为必需参数</h2><p>当我们不需要声明额外的校验或元数据时，只需不声明默认值就可以使 <code>q</code> 参数成为必需参数，例如：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">q: <span class="built_in">str</span></span><br></pre></td></tr></table></figure><p>代替：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">q: <span class="built_in">str</span> = <span class="literal">None</span></span><br></pre></td></tr></table></figure><p>但是现在我们正在用 <code>Query</code> 声明它，例如：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">q: <span class="built_in">str</span> = Query(<span class="literal">None</span>, min_length=<span class="number">3</span>)</span><br></pre></td></tr></table></figure><p>因此，当你在使用 <code>Query</code> 且需要声明一个值是必需的时，可以将 <code>...</code> 用作第一个参数值：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI, Query</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.get(<span class="params"><span class="string">&quot;/items/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">read_items</span>(<span class="params">q: <span class="built_in">str</span> = Query(<span class="params">..., min_length=<span class="number">3</span></span>)</span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;items&quot;</span>: [&#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Foo&quot;</span>&#125;, &#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Bar&quot;</span>&#125;]&#125;</span><br><span class="line">    <span class="keyword">if</span> q:</span><br><span class="line">        results.update(&#123;<span class="string">&quot;q&quot;</span>: q&#125;)</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><blockquote><p>如果你之前没见过 <code>...</code> 这种用法：它是一个特殊的单独值，它是 <a target="_blank" rel="noopener" href="https://docs.python.org/3/library/constants.html#Ellipsis">Python 的一部分并且被称为「省略号」</a>。</p><p>这将使 <strong>FastAPI</strong> 知道此查询参数是必需的。</p></blockquote><h2 id="查询参数列表-多个值"><a href="#查询参数列表-多个值" class="headerlink" title="查询参数列表 / 多个值"></a>查询参数列表 / 多个值</h2><p>当你使用 <code>Query</code> 显式地定义查询参数时，你还可以声明它去接收一组值，或换句话来说，接收多个值。</p><p>例如，要声明一个可在 URL 中出现多次的查询参数 <code>q</code>，你可以这样写：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">List</span>, <span class="type">Optional</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI, Query</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.get(<span class="params"><span class="string">&quot;/items/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">read_items</span>(<span class="params">q: <span class="type">Optional</span>[<span class="type">List</span>[<span class="built_in">str</span>]] = Query(<span class="params"><span class="literal">None</span></span>)</span>):</span></span><br><span class="line">    query_items = &#123;<span class="string">&quot;q&quot;</span>: q&#125;</span><br><span class="line">    <span class="keyword">return</span> query_items</span><br></pre></td></tr></table></figure><p>然后，输入如下网址：</p><figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://localhost:8000/items/?q=foo&amp;q=bar</span><br></pre></td></tr></table></figure><p>你会在<em>路径操作函数</em>的<em>函数参数</em> <code>q</code> 中以一个 Python <code>list</code> 的形式接收到<em>查询参数</em> <code>q</code> 的多个值（<code>foo</code> 和 <code>bar</code>）。</p><p>因此，该 URL 的响应将会是：</p><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;q&quot;</span>: [</span><br><span class="line">    <span class="string">&quot;foo&quot;</span>,</span><br><span class="line">    <span class="string">&quot;bar&quot;</span></span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><blockquote><p>要声明类型为 <code>list</code> 的查询参数，如上例所示，你需要显式地使用 <code>Query</code>，否则该参数将被解释为请求体。</p></blockquote><p>交互式 API 文档将会相应地进行更新，以允许使用多个值：</p><p><img src="https://xuqinmin.com/images/fastapi/08/image02_2.png" alt="img"></p><h3 id="具有默认值的查询参数列表-多个值"><a href="#具有默认值的查询参数列表-多个值" class="headerlink" title="具有默认值的查询参数列表 / 多个值"></a>具有默认值的查询参数列表 / 多个值</h3><p>你还可以定义在没有任何给定值时的默认 <code>list</code> 值：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">List</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI, Query</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.get(<span class="params"><span class="string">&quot;/items/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">read_items</span>(<span class="params">q: <span class="type">List</span>[<span class="built_in">str</span>] = Query(<span class="params">[<span class="string">&quot;foo&quot;</span>, <span class="string">&quot;bar&quot;</span>]</span>)</span>):</span></span><br><span class="line">    query_items = &#123;<span class="string">&quot;q&quot;</span>: q&#125;</span><br><span class="line">    <span class="keyword">return</span> query_items</span><br></pre></td></tr></table></figure><p>如果你访问：</p><figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://localhost:8000/items/</span><br></pre></td></tr></table></figure><p><code>q</code> 的默认值将为：<code>[&quot;foo&quot;, &quot;bar&quot;]</code>，你的响应会是：</p><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;q&quot;</span>: [</span><br><span class="line">    <span class="string">&quot;foo&quot;</span>,</span><br><span class="line">    <span class="string">&quot;bar&quot;</span></span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4 id="使用-list"><a href="#使用-list" class="headerlink" title="使用 list"></a>使用 <code>list</code></h4><p>你也可以直接使用 <code>list</code> 代替 <code>List [str]</code>：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI, Query</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.get(<span class="params"><span class="string">&quot;/items/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">read_items</span>(<span class="params">q: <span class="built_in">list</span> = Query(<span class="params">[]</span>)</span>):</span></span><br><span class="line">    query_items = &#123;<span class="string">&quot;q&quot;</span>: q&#125;</span><br><span class="line">    <span class="keyword">return</span> query_items</span><br></pre></td></tr></table></figure><blockquote><p>请记住，在这种情况下 FastAPI 将不会检查列表的内容。</p><p>例如，<code>List[int]</code> 将检查（并记录到文档）列表的内容必须是整数。但是单独的 <code>list</code> 不会。</p></blockquote><h2 id="声明更多元数据"><a href="#声明更多元数据" class="headerlink" title="声明更多元数据"></a>声明更多元数据</h2><p>你可以添加更多有关该参数的信息。</p><p>这些信息将包含在生成的 OpenAPI 模式中，并由文档用户界面和外部工具所使用。</p><blockquote><p>请记住，不同的工具对 OpenAPI 的支持程度可能不同。</p><p>其中一些可能不会展示所有已声明的额外信息，尽管在大多数情况下，缺少的这部分功能已经计划进行开发。</p></blockquote><p>你可以添加 <code>title</code>：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">Optional</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI, Query</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.get(<span class="params"><span class="string">&quot;/items/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">read_items</span>(<span class="params"></span></span></span><br><span class="line"><span class="params"><span class="function">    q: <span class="type">Optional</span>[<span class="built_in">str</span>] = Query(<span class="params"><span class="literal">None</span>, title=<span class="string">&quot;Query string&quot;</span>, min_length=<span class="number">3</span></span>)</span></span></span><br><span class="line"><span class="params"><span class="function"></span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;items&quot;</span>: [&#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Foo&quot;</span>&#125;, &#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Bar&quot;</span>&#125;]&#125;</span><br><span class="line">    <span class="keyword">if</span> q:</span><br><span class="line">        results.update(&#123;<span class="string">&quot;q&quot;</span>: q&#125;)</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><p>以及 <code>description</code>：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">Optional</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI, Query</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.get(<span class="params"><span class="string">&quot;/items/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">read_items</span>(<span class="params"></span></span></span><br><span class="line"><span class="params"><span class="function">    q: <span class="type">Optional</span>[<span class="built_in">str</span>] = Query(<span class="params"></span></span></span></span><br><span class="line"><span class="params"><span class="params"><span class="function">        <span class="literal">None</span>,</span></span></span></span><br><span class="line"><span class="params"><span class="params"><span class="function">        title=<span class="string">&quot;Query string&quot;</span>,</span></span></span></span><br><span class="line"><span class="params"><span class="params"><span class="function">        description=<span class="string">&quot;Query string for the items to search in the database that have a good match&quot;</span>,</span></span></span></span><br><span class="line"><span class="params"><span class="params"><span class="function">        min_length=<span class="number">3</span>,</span></span></span></span><br><span class="line"><span class="params"><span class="params"><span class="function">    </span>)</span></span></span><br><span class="line"><span class="params"><span class="function"></span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;items&quot;</span>: [&#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Foo&quot;</span>&#125;, &#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Bar&quot;</span>&#125;]&#125;</span><br><span class="line">    <span class="keyword">if</span> q:</span><br><span class="line">        results.update(&#123;<span class="string">&quot;q&quot;</span>: q&#125;)</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><h2 id="别名参数"><a href="#别名参数" class="headerlink" title="别名参数"></a>别名参数</h2><p>假设你想要查询参数为 <code>item-query</code>。</p><p>像下面这样：</p><figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://127.0.0.1:8000/items/?item-query=foobaritems</span><br></pre></td></tr></table></figure><p>但是 <code>item-query</code> 不是一个有效的 Python 变量名称。</p><p>最接近的有效名称是 <code>item_query</code>。</p><p>但是你仍然要求它在 URL 中必须是 <code>item-query</code>…</p><p>这时你可以用 <code>alias</code> 参数声明一个别名，该别名将用于在 URL 中查找查询参数值：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">Optional</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI, Query</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.get(<span class="params"><span class="string">&quot;/items/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">read_items</span>(<span class="params">q: <span class="type">Optional</span>[<span class="built_in">str</span>] = Query(<span class="params"><span class="literal">None</span>, alias=<span class="string">&quot;item-query&quot;</span></span>)</span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;items&quot;</span>: [&#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Foo&quot;</span>&#125;, &#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Bar&quot;</span>&#125;]&#125;</span><br><span class="line">    <span class="keyword">if</span> q:</span><br><span class="line">        results.update(&#123;<span class="string">&quot;q&quot;</span>: q&#125;)</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><h2 id="弃用参数"><a href="#弃用参数" class="headerlink" title="弃用参数"></a>弃用参数</h2><p>现在假设你不再喜欢此参数。</p><p>你不得不将其保留一段时间，因为有些客户端正在使用它，但你希望文档清楚地将其展示为已弃用。</p><p>那么将参数 <code>deprecated=True</code> 传入 <code>Query</code>：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> <span class="type">Optional</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI, Query</span><br><span class="line"></span><br><span class="line">app = FastAPI()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@app.get(<span class="params"><span class="string">&quot;/items/&quot;</span></span>)</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">def</span> <span class="title">read_items</span>(<span class="params"></span></span></span><br><span class="line"><span class="params"><span class="function">    q: <span class="type">Optional</span>[<span class="built_in">str</span>] = Query(<span class="params"></span></span></span></span><br><span class="line"><span class="params"><span class="params"><span class="function">        <span class="literal">None</span>,</span></span></span></span><br><span class="line"><span class="params"><span class="params"><span class="function">        alias=<span class="string">&quot;item-query&quot;</span>,</span></span></span></span><br><span class="line"><span class="params"><span class="params"><span class="function">        title=<span class="string">&quot;Query string&quot;</span>,</span></span></span></span><br><span class="line"><span class="params"><span class="params"><span class="function">        description=<span class="string">&quot;Query string for the items to search in the database that have a good match&quot;</span>,</span></span></span></span><br><span class="line"><span class="params"><span class="params"><span class="function">        min_length=<span class="number">3</span>,</span></span></span></span><br><span class="line"><span class="params"><span class="params"><span class="function">        max_length=<span class="number">50</span>,</span></span></span></span><br><span class="line"><span class="params"><span class="params"><span class="function">        regex=<span class="string">&quot;^fixedquery$&quot;</span>,</span></span></span></span><br><span class="line"><span class="params"><span class="params"><span class="function">        deprecated=<span class="literal">True</span>,</span></span></span></span><br><span class="line"><span class="params"><span class="params"><span class="function">    </span>)</span></span></span><br><span class="line"><span class="params"><span class="function"></span>):</span></span><br><span class="line">    results = &#123;<span class="string">&quot;items&quot;</span>: [&#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Foo&quot;</span>&#125;, &#123;<span class="string">&quot;item_id&quot;</span>: <span class="string">&quot;Bar&quot;</span>&#125;]&#125;</span><br><span class="line">    <span class="keyword">if</span> q:</span><br><span class="line">        results.update(&#123;<span class="string">&quot;q&quot;</span>: q&#125;)</span><br><span class="line">    <span class="keyword">return</span> results</span><br></pre></td></tr></table></figure><p>文档将会像下面这样展示它：</p><p><img src="https://xuqinmin.com/images/fastapi/08/image01_2.png" alt="img"></p><h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>你可以为查询参数声明额外的校验和元数据。</p><p>通用的校验和元数据：</p><ul><li><code>alias</code></li><li><code>title</code></li><li><code>description</code></li><li><code>deprecated</code></li></ul><p>特定于字符串的校验：</p><ul><li><code>min_length</code></li><li><code>max_length</code></li><li><code>regex</code></li></ul><p>在这些示例中，你了解了如何声明对 <code>str</code> 值的校验。</p><p>请参阅下一章节，以了解如何声明对其他类型例如数值的校验。</p></div><div class="article-footer"><blockquote class="mt-2x"><ul class="post-copyright list-unstyled"><li class="post-copyright-link hidden-xs"><strong>本文链接：</strong> <a href="https://xuqinmin.gitee.io/posts/732748453.html" title="FastAPI | 教程 | 查询参数和字符串校验" target="_blank" rel="external">https://xuqinmin.gitee.io/posts/732748453.html</a></li><li class="post-copyright-license"><strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN协议</a> 许可协议。转载请注明出处！</li></ul></blockquote><div class="panel panel-default panel-badger"><div class="panel-body"><figure class="media"><div class="media-left"><a href="https://xuqinmin.com/xuqinmin12" target="_blank" class="img-burn thumb-sm visible-lg"><img src="/images/avatar.jpg" class="img-rounded w-full" alt=""></a></div><div class="media-body"><h3 class="media-heading"><a href="https://xuqinmin.com/xuqinmin12" target="_blank"><span class="text-dark">XUQM</span><small class="ml-1x">Android开发</small></a></h3><div>一个啥也不会的Android开发，励志转型ios开发，后来放弃了。还想搞后台，后台不让！python也不同意！！！</div></div></figure></div></div></div></article><section id="comments"><div id="vcomments"></div></section></div><nav class="bar bar-footer clearfix" data-stick-bottom><div class="bar-inner"><ul class="pager pull-left"><li class="prev"><a href="/posts/1443831343.html" title="FastAPI | 教程 | 路径参数和数值校验"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;上一篇</span></a></li><li class="next"><a href="/posts/356024147.html" title="FastAPI | 教程 | 请求体"><span>下一篇&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a></li><li class="toggle-toc"><a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false" title="文章目录" role="button"><span>[&nbsp;</span><span>文章目录</span> <i class="text-collapsed icon icon-anchor"></i> <i class="text-in icon icon-close"></i> <span>]</span></a></li></ul><div class="bar-right"><div class="share-component" data-sites="weibo,qq,wechat,facebook,twitter" data-mobile-sites="weibo,qq,wechat"></div></div></div></nav></main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter"><div style="width:300px;margin:0 auto"><a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=37132902372892" style="display:inline-block;text-decoration:none"><img src="https://www.beian.gov.cn/img/new/gongan.png" style="float:left"><p style="float:left;margin:0 0 0 5px;color:#939393">鲁公网安备 37132902372892号</p></a></div><div style="width:300px;margin:0 auto"><a target="_blank" href="https://beian.miit.gov.cn/" style="display:inline-block;text-decoration:none"><p style="float:left;margin:0 0 0 5px;color:#939393">&nbsp;&nbsp;&nbsp;&nbsp; 鲁ICP备20018775号-3</p></a></div><div>&nbsp;</div><div>&nbsp;</div><ul class="social-links"><li><a href="https://github.com/xuqm" target="_blank" title="Github" data-toggle="tooltip" data-placement="top"><i class="icon icon-github"></i></a></li><li><a href="https://gitee.com/xuqinmin" target="_blank" title="Gitee" data-toggle="tooltip" data-placement="top"><i class="icon icon-gitee"></i></a></li><li><a href="/atom.xml" target="_blank" title="Rss" data-toggle="tooltip" data-placement="top"><i class="icon icon-rss"></i></a></li></ul><div class="copyright">&copy; 2023 Xuqm<div class="publishby">Theme by <a href="https://github.com/cofess" target="_blank">cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.</div></div></footer><script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script><script>window.jQuery||document.write('<script src="js/jquery.min.js"><\/script>')</script><script src="/js/plugin.min.js"></script><script src="/js/application.js"></script><script>window.INSIGHT_CONFIG={TRANSLATION:{POSTS:"文章",PAGES:"页面",CATEGORIES:"分类",TAGS:"标签",UNTITLED:"(未命名)"},ROOT_URL:"/",CONTENT_URL:"/content.json"}</script><script src="/js/insight.js"></script><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script><script src="//cdn.jsdelivr.net/npm/valine"></script><script type="text/javascript">var GUEST=["nick","mail","link"],meta=(meta="nick,mail,link").split(",").filter(function(e){return-1<GUEST.indexOf(e)});new Valine({el:"#vcomments",verify:!1,notify:!1,appId:"mRlIqh4MAdByI85z02yNYA2w-gzGzoHsz",appKey:"3LKdn7pI9XqvCqgBhFdLoWgw",placeholder:"来都来了，玩玩呗~~~",avatar:"mm",meta:meta,pageSize:"10",visitor:!1})</script><script src="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.3.5/dist/jquery.fancybox.min.js"></script><script>$(document).ready(function(){$("article img").not("[hidden]").not(".panel-body img").each(function(){var a,t,n=$(this),e=n.attr("alt"),r=n.parent("a");r.length<1&&(-1!=(t=(a=this.getAttribute("src")).lastIndexOf("?"))&&(a=a.substring(0,t)),r=n.wrap('<a href="'+a+'"></a>').parent("a")),r.attr("data-fancybox","images"),e&&r.attr("data-caption",e)}),$().fancybox({selector:'[data-fancybox="images"]',hash:!1,loop:!1})})</script></body></html>